import { createWebHashHistory, createRouter } from "vue-router";
import { getPage } from "../api/page";
let routes = [];
const res = await getPage();
const list = res.data;
list.forEach((element) => {
  if (element.father == 0) {
    let route = {
      id: element.id,
      path: element.path,
      name: element.name,
      component: () =>
        import(/*@vite-ignore*/ "../views/" + element.component + "/index.vue"),
      meta: {
        title: element.title,
        icon: element.icon,
      },
      children: [],
      redirect: element.redirect,
      father: element.father,
    };
    routes.push(route);
  }
});
list.forEach((element) => {
  for (let index = 0; index < routes.length; index++) {
    if (element.father == routes[index].id) {
      routes[index].children = routes[index].children
        ? routes[index].children
        : [];
      let route = {
        id: element.id,
        path: element.path,
        name: element.name,
        component: () =>
          import(
            /*@vite-ignore*/ "../views/" + element.component + "/index.vue"
          ),
        meta: {
          title: element.title,
          icon: element.icon,
        },
        children: [],
        redirect: element.redirect,
        father: element.father,
      };
      routes[index].children.push(route);
    }
  }
});
localStorage.setItem("navicateList", JSON.stringify(routes));
routes = [
  {
    path: "/",
    name: "Home",
    component: () => import("@/views/layout/index.vue"),
    redirect: "/home-page",
    children: routes
  }, {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/register/index.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/error/404.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// router守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  const lifespan = localStorage.getItem("lifespan");
  if (token) {
    if (lifespan < Date.now() - 1000 * 60 * 60 * 24 * 2) {
      localStorage.removeItem("token");
      localStorage.removeItem("lifespan");
      next({
        path: "/login",
      });
    } else {
      next();
    }
  } else {
    if (to.path == "/login" || to.path == "/register") {
      next();
    } else {
      next({
        path: "/login",
      });
    }
  }
});

export default router;
